# Bind Certificate to IIS Site
param(
    [Parameter(Mandatory=$true)]
    [string]$SiteName,

    [Parameter(Mandatory=$true)]
    [string]$Thumbprint,

    [Parameter(Mandatory=$false)]
    [string]$HostName = "",

    [Parameter(Mandatory=$false)]
    [string]$IP = "*",

    [Parameter(Mandatory=$false)]
    [int]$Port = 443
)

Import-Module WebAdministration

try {
    # 检查站点是否存在
    $site = Get-Website -Name $SiteName -ErrorAction Stop
    if (-not $site) {
        Write-Error "Site not found: $SiteName"
        exit 1
    }

    # 移除旧的 HTTPS 绑定
    $oldBindings = Get-WebBinding -Name $SiteName -Protocol "https"
    if ($HostName) {
        $oldBindings = $oldBindings | Where-Object { $_.bindingInformation -like "*$HostName" }
    }
    $oldBindings | Remove-WebBinding

    # 创建新绑定
    $bindingInfo = "${IP}:${Port}:${HostName}"
    New-WebBinding -Name $SiteName -Protocol "https" -BindingInformation $bindingInfo -ErrorAction Stop

    # 绑定证书
    $binding = Get-WebBinding -Name $SiteName -Protocol "https" | Where-Object { $_.bindingInformation -eq $bindingInfo }
    $binding.AddSslCertificate($Thumbprint, "My")

    Write-Output "Certificate bound successfully to $SiteName"
    exit 0

} catch {
    Write-Error $_.Exception.Message
    exit 1
}
